package com.zx.designpattern.model.impl;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.midcent.networklib.interfac.RequestListener;
import com.orhanobut.logger.Logger;
import com.zx.designpattern.model.db.dbmanager.DbManager;
import com.zx.designpattern.model.db.greendao.TagModDao;
import com.zx.designpattern.model.http.BaseEntity;
import com.zx.designpattern.model.http.myvolley.VolleyManager;
import com.zx.designpattern.model.http.volleyrequest.TagsRequest;
import com.zx.designpattern.model.IBaseModel;
import com.zx.designpattern.model.bean.TagMod;
import com.zx.designpattern.utils.ListUtils;
import com.zx.designpattern.utils.ToastUtils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zx.designpattern.BaseApplication.getAppContext;
import static com.zx.designpattern.model.http.URLUtils.GET_TAG_LIST;
import static com.zx.designpattern.model.impl.TagModelImpl.LoadCode.loadFromDB;
import static com.zx.designpattern.model.impl.TagModelImpl.LoadCode.loadFromNet;
import static com.zx.designpattern.model.impl.TagModelImpl.LoadCode.postFormToDB;

/**
 * Created by zhoux on 2018/3/5.
 * 注释：
 */

public class TagModelImpl implements IBaseModel {

    /**
     * 加载/提交数据逻辑code
     */
    public interface LoadCode {
        int loadFromNet = 1;//网络请求
        int loadFromDB = 2;//数据库请求
        //        ... 还可以自定义其他逻辑，需要在loadData/postData中增加相应的逻辑，例：
        int postFormToDB = 3;//上传数据
    }

    //数据库造作类
    TagModDao mTagModDao = DbManager.getTagModDao(getAppContext());

    @Override
    public void loadData(CallBack mCallBack) {
        //retrofit 方式请求数据
        Map<String, String> map = new HashMap();
        map.put("orderBy", "id asc");
//        RetroFactory.getInstance().create(TagService.class).getList(map).compose(BaseComApi.background()).doOnError(Throwable::printStackTrace)
//                .doOnNext(baseEntity -> {
//                    if (baseEntity.isSuccess()) {
//                        List<TagMod> list = baseEntity.getData();
//                        mCallBack.success(list);
//                    } else {
//                    }
//                })
//.subscribe();


        TagsRequest request = new TagsRequest(getAppContext());
        request.setContentBody();
        request.setRequestListener(new RequestListener() {
            @Override
            public void onResultSuccess(Object obj) {
                Gson gson = new Gson();
                Type type = new TypeToken<ArrayList<TagMod>>() {
                }.getType();

                Log.e("[obj.toString()]", obj.toString());
                //                        List<TagMod> list = baseEntity.getData();
                List<TagMod> list = gson.fromJson(obj.toString(), type);
                mCallBack.success(list);
            }

            @Override
            public void onError(Object obj) {
                ToastUtils.show(obj.toString());
                mCallBack.fail(obj.toString());
            }
        });
        request.get();
    }

    @Override
    public void loadData(int code, final CallBack mCallBack) {
        switch (code) {
            case loadFromNet:
                //网络请求数据逻辑处理
                loadDataVolleyTest(mCallBack);
                break;
            case loadFromDB:
                //数据库请求数据逻辑处理
                loadDataGreenDaoTest(mCallBack);
                break;
            default:
                break;
        }
    }

    @Override
    public void postData(Object data, CallBack mCallBack) {

    }

    @Override
    public void postData(int code, Object data, CallBack mCallBack) {
        switch (code) {
            case postFormToDB:
                // TODO: 2018/3/22 提交数据 到数据库
                int nums = (int) data;

                for (int i = 0; i < nums; i++) {
                    TagMod mod = new TagMod();
                    mod.setId("xxx");
                    mod.setName("1先擦");
                    mTagModDao.insertOrReplace(mod);
                }
                List<TagMod> list = mTagModDao.loadAll();
                mCallBack.success(list);
                break;
            default:
                break;
        }
    }

    private void loadDataGreenDaoTest(final CallBack mCallBack) {
        List<TagMod> list = mTagModDao.loadAll();
        Logger.d("here");
        if (ListUtils.isNotEmpty(list)) {
            Logger.d(list);
            mCallBack.success(list);
            return;
        }
    }

    private void loadDataVolleyTest(final CallBack mCallBack) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("orderBy", "id asc");
        TypeToken typeToken = new TypeToken<BaseEntity<ArrayList<TagMod>>>() {
        };
        CallBack callBack = new IBaseModel.CallBack<BaseEntity<ArrayList<TagMod>>>() {
            @Override
            public void success(BaseEntity<ArrayList<TagMod>> data) {
                List<TagMod> list = data.getData();
                for (int i = 0; i < ListUtils.getSize(list); i++) {
                    mTagModDao.insertOrReplace(list.get(i));
                }
                mCallBack.success(list);
            }


            @Override
            public void fail(Object data) {
                mCallBack.fail(data);

            }
        };

        VolleyManager.get(GET_TAG_LIST, map, callBack, typeToken);

    }


}
